package com.zt.securityTest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.securityTest.entity.LoginUser;
import com.zt.securityTest.entity.User;
import com.zt.securityTest.mapper.MenuMapper;
import com.zt.securityTest.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;


/**
 * time: 2024.11.15 17:37
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (!StringUtils.hasText(username)){
            throw new InternalAuthenticationServiceException("");
        }

        //1.根据用户名查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));

        if (user == null){
            throw new UsernameNotFoundException("");
        }
        //2.赋予权限
        List<String> menus = menuMapper.getMenuByUserId(user.getId());

        //3.返回userDetail对象
        LoginUser loginUser = new LoginUser(user,menus );
        return loginUser;
    }
}
